﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using ShredTheLog.Api.DataContracts;
using ShredTheLog.Api;

namespace ShredTheLog.Translation
{
    public sealed class FilteringTranslator : ITranslatorBase
    {
        private ITranslatorBase _innerTranslator;

        [ContractInvariantMethod]
        private void ObjectInvariant()
        {
            Contract.Invariant(_innerTranslator != null);
        }

        public FilteringTranslator(ITranslatorBase innerTranslator)
        {
            Contract.Requires(innerTranslator != null);

            _innerTranslator = innerTranslator;
        }

        public IObservable<TranslateResponse> Translate(TranslateRequest translateRequest, bool ignoreErrors)
        {
            if (String.IsNullOrWhiteSpace(translateRequest.Text) || (translateRequest.SourceLanguage.HasValue && translateRequest.SourceLanguage.Value == translateRequest.TargetLanguage))
            {
                var result = Observable.Empty<TranslateResponse>();
                Contract.Assume(result != null);
                return result;
            }
            else
            {
                var result = 
                    _innerTranslator.Translate(translateRequest, ignoreErrors)
                    .Where(response => response.DetectedSourceLanguage != translateRequest.TargetLanguage && !String.IsNullOrWhiteSpace(response.Text) && String.Compare(response.Text, translateRequest.Text, true) != 0);
                Contract.Assume(result != null);
                return result;
            }
        }

        public IObservable<DetectResponse> Detect(string text)
        {
            return _innerTranslator.Detect(text);
        }

        public IEnumerable<Language> SupportedLanguages { get { return _innerTranslator.SupportedLanguages; } }
    }
}
